<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Web Socket 定时刷新</title>
<script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/sockjs-client/dist/sockjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/stompjs/lib/stomp.min.js"></script>
</head>

<body>
	<h1>Web Socket 定时刷新</h1>
	<p>Online Users: <b id="online-users">0</b></p>
	<p>Online message:<b id="online-message"></b></p>
	
	<div id="updates"></div>
</body>

<script type="text/javascript">
$(function(){
	websocket(1);
});

function websocket(data){
	var socket = new SockJS('/websocket');
	var stompClient = Stomp.over(socket);

	//stomp客户端建立连接
	stompClient.connect({data:data}, function(frame) {
		console.log('Connected: ' + frame);
		
		//订阅不同频道（“/topic/updates”，“/topic/getResponse”），接受消息
		stompClient.subscribe('/topic/updates', function(update) {
			var updateElement = document.getElementById('updates');
			updateElement.innerHTML = update.body + '<br/>';
		});
		
 		stompClient.subscribe('/topic/getResponse', function (response) { //2
	           var elem = document.getElementById("online-users");
	           elem.textContent = response.body;
	    }); 
 		
        //刚连接的时候执行，初始化数据，只执行一次
        stompClient.subscribe('/app/welcome', function (response) {
            var elem = document.getElementById("online-users");
            elem.textContent = response.body;
        }); 
        
    	stompClient.subscribe('/topic/message', function (response) { 
	           var elem = document.getElementById("online-message");
	           elem.textContent = response.body;
	    }); 
    	
	});
	
    //监听窗口关闭
    window.onbeforeunload = function (event) {
        socket.close()
    }
}
</script>
</html>